package com.akk.platform.oem.business;

import com.akk.module.avs.entity.AvsYbLoanType;
import com.akk.module.avs.model.request.AvsYbLoanTypeReq;
import com.akk.module.avs.service.AvsYbLoanTypeService;
import com.akk.module.upload.service.PictureService;
import com.akk.utils.PageUtils;
import com.akk.utils.Query;
import com.akk.utils.RestResponse;
import com.akk.utils.ShiroUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

import java.util.List;
import java.util.Map;

@Component
public class YbLoanTypeBusiness {

    @Autowired
    private AvsYbLoanTypeService ybLoanTypeService;

    @Autowired
    private PictureService pictureService;

    public RestResponse list(Query query){
        PageHelper.startPage(query.getPage(),query.getLimit());
        List<AvsYbLoanType> list = ybLoanTypeService.findAll(ShiroUtils.getAdmin().getAppId());
        return RestResponse.build(PageUtils.buildPage(list,(int) new PageInfo<>(list).getTotal(),query));
    }

    public RestResponse save(AvsYbLoanTypeReq req, BindingResult bindingResult){
        if (bindingResult.hasErrors())
            return RestResponse.build("error",bindingResult.getFieldError().getDefaultMessage(),null);
        Map<String,Object> result = pictureService.uploadPicture(req.getIcon());
        if (result.get("status").toString().equals("1"))
            return RestResponse.build("error","文件上传失败",null);
        req.setLoanTypeIcon(result.get("url").toString());
        req.setLoanTypeAppId(ShiroUtils.getAdmin().getAppId());
        ybLoanTypeService.save(req);
        return RestResponse.build("200","",null);
    }

    public RestResponse update(AvsYbLoanTypeReq req){
        if (req.getIcon() != null){
            Map<String,Object> result = pictureService.uploadPicture(req.getIcon());
            if (result.get("status").toString().equals("1"))
                return RestResponse.build("error","文件上传失败",null);
            if (!StringUtils.isEmpty(req.getLoanTypeIcon()))
                pictureService.removeFile(req.getLoanTypeIcon());
            req.setLoanTypeIcon(result.get("url").toString());
        }
        ybLoanTypeService.update(req);
        return RestResponse.build("200","success",null);
    }

    public RestResponse info(Long typeId){
        AvsYbLoanType type = ybLoanTypeService.findById(typeId);
        if (type == null)
            return RestResponse.build("1","信息不存在",null);
        return RestResponse.build("200","success",type);
    }

    public RestResponse delete(Long typeId){
        ybLoanTypeService.delete(typeId);
        return RestResponse.build("200","success",null);
    }

}
